package cn.tedu.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 聊天室服务端
 */
class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        while (true) {
            try {
                //2.构建输入流对象（字符缓冲输入流）
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream(), StandardCharsets.UTF_8));
                //3.通过此对象读取数据
                String data = null;
                while ((data = br.readLine()) != null) {
                    System.out.println("从客户端读取到的数据:" + data);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ThreadChatServer {
    //定义服务端的serverSocket属性
    private ServerSocket serverSocket;
    public static final int PORT;
    static {
        PORT=8888;//可以从配置文件读取
    }
    public ThreadChatServer(){
        try {
            System.out.println("服务器正在启动");
            serverSocket=new ServerSocket(PORT);
            System.out.println("服务器启动成功,正在"+PORT+"端口上监听");
        }catch (IOException e){
            e.printStackTrace();//让运维知道哪里出错了(后续这些信息记录到日志文件)
            System.out.println("服务器启动失败");
            System.exit(-1);
        }
    }
    public void start() {
        while(true) {
        try {
            //1.接收客户端的连接(主线程-接线员)
            Socket socket = serverSocket.accept();
            System.out.println("客户端连接成功");
            //2.启动线程出力客户端请求
            new Thread(new ClientHandler(socket)).start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
    //启动服务读取数据
    public static void main(String[] args) {
        new ThreadChatServer().start();
    }
}
